package cn.leelei.springdata.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 配置文件类
 * @author Administrator
 *
 */
@Configuration
@EnableJpaRepositories(basePackages="cn.leelei.springdata.repository")//指定持久层的包
@PropertySource("classpath:jdbc.properties")
@EnableTransactionManagement
public class ApplicationConfig {

	@Value("${jdbc.username}")
	private String userNaame;
	@Value("${jdbc.password}")
	private String passWord;
	@Value("${jdbc.url}")
	private String url;
	@Value("${jdbc.driver}")
	private String driverClass;

	/**
	 * 分离属性文件
	 * 
	 * @return
	 */
	@Bean
	public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {

		return new PropertySourcesPlaceholderConfigurer();

	}

	/**
	 * 配置数据源
	 * 
	 * @return
	 */
	@Bean
	public DataSource dataSource() {

		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setUsername(userNaame);
		dataSource.setPassword(passWord);
		dataSource.setUrl(url);
		dataSource.setDriverClassName(driverClass);
		/*
		 * // 使用内嵌的数据源 EmbeddedDatabaseBuilder builder = new
		 * EmbeddedDatabaseBuilder(); return
		 * builder.setType(EmbeddedDatabaseType.HSQL).build();
		 */
		return dataSource;

	}

	/**
	 * 配置实体管理工厂bean
	 * 
	 * @return
	 */
	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
		
		LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
		
		//设置扫描实体类包
		factory.setPackagesToScan("cn.leelei.springdata.entity");
		//设置数据源
		factory.setDataSource(dataSource());
		//指定jpa实现商
		HibernateJpaVendorAdapter jpaVendorAdapter  = new HibernateJpaVendorAdapter();
		jpaVendorAdapter.setGenerateDdl(true);
		//显示sql语句
		jpaVendorAdapter.setShowSql(true);
		factory.setJpaVendorAdapter(jpaVendorAdapter);
		return factory;
	}
	/**
	 * 配置事务管理器
	 * @return
	 */
	@Bean
	public PlatformTransactionManager transactionManager() {
		JpaTransactionManager txManager = new JpaTransactionManager();
		txManager.setEntityManagerFactory(entityManagerFactory().getObject());
		return txManager;

	}
}
